package com.xtaller.test.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.test.config.annotation.Token;
import lombok.var;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @version V1.0
 * @author: Taller
 * @date: 2019-08-09
 * @Description:
 */
@Component
public class TokenInter implements HandlerInterceptor {
    /**
     * 只要在方法上添加 token注解表示 这个方法的执行需要token认证 如果没有则不认证
     *
     * */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        var access_token = request.getHeader("token");

        Token token = null;
        HandlerMethod handlerMethod = (HandlerMethod)handler;

        token = handlerMethod.getMethod().getAnnotation(Token.class);

        if(token == null){
            return true;
        }

        if(access_token == null || "".equals(access_token)){
            // http状态码
            response.setStatus(400);
            response.getWriter().write("token信息不能为空");
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
